Skip to content

Add community discussions feature#572

Closed
arpit2006 wants to merge 3 commits into
GitMetricsLab:mainfrom
arpit2006:feature/community-discussions
Closed

Add community discussions feature#572
arpit2006 wants to merge 3 commits into
GitMetricsLab:mainfrom
arpit2006:feature/community-discussions

Conversation

@arpit2006
Copy link
Copy Markdown
Contributor

@arpit2006 arpit2006 commented May 27, 2026

Related Issue


Description

Added a dedicated community discussion section to GitHub Tracker so users can create posts, share ideas, ask questions, and interact with other developers. This includes a discussion feed, create/edit/delete actions, comments, likes, search, category filtering, trending discussions, responsive UI, and dark mode support.

I also fixed the login issue because it was necessary for this feature creation and for authenticated discussion actions to work properly.


How Has This Been Tested?

  • Verified the frontend build with npm run build
  • Verified the discussion backend route loads successfully
  • Verified signup/login flow against the backend
  • Verified discussion creation through the API

Screenshots (if applicable)

image ---

Type of Change

  • Bug fix
  • New feature
  • Code style update
  • Breaking change
  • Documentation update
  • Here the Authentication was also fixed as it was required to implement this feature

Summary by CodeRabbit

Release Notes

  • New Features

    • Community discussion feed now available with ability to create, edit, and delete discussions
    • Like discussions and add comments to engage with the community
    • Search, filter by category/tags, and sort discussions by recent or trending activity
    • Trending sidebar displays popular discussions and community statistics
    • Navigation updated with Community link
  • Improvements

    • Authentication system enhanced for better session handling

Review Change Stack

@netlify
Copy link
Copy Markdown

netlify Bot commented May 27, 2026

Deploy Preview for github-spy ready!

Name Link
🔨 Latest commit 78f795a
🔍 Latest deploy log https://app.netlify.com/projects/github-spy/deploys/6a16eb3ffa27db000884bdfe
😎 Deploy Preview https://deploy-preview-572--github-spy.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 27, 2026

Warning

Review limit reached

@arpit2006, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 15 minutes and 29 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 76564c11-7ae8-4080-a36a-bdbd45bca103

📥 Commits

Reviewing files that changed from the base of the PR and between e675744 and 78f795a.

📒 Files selected for processing (9)
  • backend/data/discussions.json
  • backend/data/users.json
  • backend/models/Discussion.js
  • backend/routes/auth.js
  • backend/routes/discussions.js
  • backend/server.js
  • src/Routes/Router.tsx
  • src/pages/Community/Community.tsx
  • src/pages/Login/Login.tsx
📝 Walkthrough

Walkthrough

This PR implements a complete community discussion feature, adding file-backed discussion CRUD endpoints, authenticated user interactions (likes/comments), Mongoose schemas, form-based frontend UI, and non-MongoDB fallback authentication to enable deployment without a database.

Changes

Community Discussion Feature

Layer / File(s) Summary
Backend Models and Validators
backend/data/discussions.json, backend/data/users.json, backend/models/Discussion.js, backend/validators/discussionValidator.js
Mongoose DiscussionSchema with embedded comments, Zod validation for discussion title/body/category/tags and comment text, plus seed data for users and discussions.
Backend Discussion API
backend/routes/discussions.js
File-backed discussion router implementing GET (with filtering/sorting), POST (create), PUT (update, author-only), DELETE (author-only), POST likes (toggle), and POST comments (append) with proper status codes and updatedAt timestamps.
Backend Auth Non-Mongo Support
backend/routes/auth.js
Extended /signup, /login, /logout to support non-Mongo file-backed authentication using users.json, bcrypt hashing, and session persistence via req.session.authUser when MONGO_URI is absent.
Backend Server Integration
backend/server.js
CORS restricted to CLIENT_URL origin, conditional middleware to mirror session user onto req.user for non-Mongo mode, discussion route registration, and non-blocking MongoDB connection with fallback server startup.
Frontend Routing and Navigation
src/App.tsx, src/Routes/Router.tsx, src/components/Navbar.tsx
Main layout changed to full-width column, /community and /discussions routes registered to Community component, and "Community" link added to desktop and mobile navbars.
Frontend Community Page Implementation
src/pages/Community/Community.tsx
Full-featured React page fetching discussions with withCredentials, rendering a form for create/edit, discussion feed with truncated comments and like/delete/edit controls (author-only), comment drafts, category/tag/search filtering, trending computation, and unauthorized messaging.
Frontend Auth Credential Handling
src/pages/Login/Login.tsx, src/pages/Signup/Signup.tsx
Backend URL fallback to http://localhost:5000, and withCredentials: true added to auth POST requests to support session-based authentication.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant CommunityUI as Community.tsx
  participant BackendAPI as Discussion API
  participant SessionAuth as Session/Auth
  User->>CommunityUI: Load page / filter discussions
  CommunityUI->>BackendAPI: GET / with params
  BackendAPI->>CommunityUI: Return discussions + categories
  User->>CommunityUI: Create/Edit discussion
  CommunityUI->>BackendAPI: POST / or PUT /:id
  BackendAPI->>CommunityUI: Return created/updated discussion
  CommunityUI->>User: Refresh feed, show success
  User->>CommunityUI: Like or comment
  CommunityUI->>BackendAPI: POST /:id/likes or POST /:id/comments
  BackendAPI->>CommunityUI: Return updated discussion
  CommunityUI->>User: Update engagement UI
  User->>CommunityUI: Attempt protected action (unauthorized)
  BackendAPI->>CommunityUI: 401 response
  CommunityUI->>User: Show sign-in message
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • GitMetricsLab/github_tracker#467: Overlaps on CORS origin restriction and withCredentials auth cookie hardening in both backend/server.js and frontend auth pages.
  • GitMetricsLab/github_tracker#269: Related signup form submission refactor in src/pages/Signup/Signup.tsx with withCredentials and backend URL changes.
  • GitMetricsLab/github_tracker#277: Navbar test updates in src/components/__test__/Navbar.test.tsx are directly impacted by the new "Community" navigation link addition.

Suggested labels

type:feature, level:advanced, quality:clean

Poem

🐰 A rabbit hops with glee,
For discussions now run wild and free!
No database walls, just files so light,
Community connects—day and night! 🌙

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Add community discussions feature' clearly summarizes the primary change—implementing a community discussion section with all related features.
Description check ✅ Passed The PR description covers the template structure with Related Issue, Description, Testing, Screenshots, and Type of Change sections mostly complete.
Linked Issues check ✅ Passed All major acceptance criteria from issue #549 are met: discussion creation [#549], commenting [#549], responsive feed [#549], authentication [#549], and UI/UX implementation [#549].
Out of Scope Changes check ✅ Passed Changes to Login/Signup components and auth routes are justified as necessary fixes for authenticated discussion actions, staying within scope.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@arpit2006
Copy link
Copy Markdown
Contributor Author

@mehul-m-prajapati, Requesting review!
While implementing this feature, I also resolved the authentication issue since it was essential for this functionality.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/server.js (1)

25-29: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Missing fallback or validation for SESSION_SECRET.

express-session requires a secret to sign session cookies. If SESSION_SECRET is undefined, the server may fail to start or use an insecure empty string. Add validation or a fallback with a warning.

Proposed fix
+if (!process.env.SESSION_SECRET) {
+    logger.warn('SESSION_SECRET is not set; using insecure default (development only)');
+}
 app.use(session({
-    secret: process.env.SESSION_SECRET,
+    secret: process.env.SESSION_SECRET || 'insecure-dev-secret-change-me',
     resave: false,
     saveUninitialized: false,
 }));
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/server.js` around lines 25 - 29, The session middleware uses
process.env.SESSION_SECRET directly which can be undefined; validate and provide
a non-empty secret (or abort startup) before calling app.use(session(...)). Add
code that reads SESSION_SECRET into a variable, checks it's a non-empty string,
and if missing either throw an error/process.exit(1) or generate a secure
fallback while logging a clear warning; then pass that validated secret into the
session config used in app.use(session({ secret: secretVar, resave: false,
saveUninitialized: false })). Ensure the check runs at startup so the session
middleware never receives an undefined/empty secret.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/data/users.json`:
- Around line 3-20: The seeded user file backend/data/users.json contains
real-looking emails and bcrypt password hashes for entries with ids
"a95e96b8-c655-4122-b949-9a9a2e166e96", "7a565adc-7c6b-4254-bd38-874c22d88892",
and "a6775248-35ef-410c-b529-220e350210f2"; replace those with synthetic/demo
data by removing or replacing personal emails with clearly synthetic addresses
(e.g., user+N@example.invalid) and remove actual password hashes, either
replacing them with a null/placeholder password field or generate ephemeral
hashes at bootstrap time (documented in README); ensure usernames remain
non-identifying or anonymized and update any code that depends on hardcoded
hashes to derive credentials at setup instead.

In `@backend/models/Discussion.js`:
- Around line 46-68: The tags, likes, and comments fields on the Discussion
schema can be undefined downstream; update the schema definition for the array
fields (tags, likes, comments) to include defaults of empty arrays so consumers
can safely call .length/.includes/.map; specifically add default: [] to the tags
array element definition, the likes array definition, and the comments array
(which uses CommentSchema) in Discussion.js to guarantee a consistent shape.

In `@backend/routes/auth.js`:
- Around line 26-41: readUsers/writeUsers use a non-atomic read-modify-write on
usersFile causing lost concurrent signups; fix by gating writes with a file lock
or atomic write/rename: in writeUsers (and any signup flow that reads then
writes) acquire a lock on usersFile (e.g., proper-lockfile.lock with retries),
perform fs.writeFile to a temp file followed by fs.rename or write directly
while holding the lock, then always release the lock in a finally block; ensure
ensureUsersFile and any callers of readUsers/writeUsers honor the lock to
prevent concurrent read/modify/write races.

In `@backend/routes/discussions.js`:
- Around line 93-113: The route-level validatePayload is weaker than the shared
validator contract; update the discussions route to reuse or mirror the shared
validators instead of the current ad-hoc checks: replace/augment validatePayload
(and the create/update/comment handlers that call it) to enforce the same
constraints as the shared validator (max title length, max body length, max
category length, max tags count and per-tag length, and tag type checks), or
import and call the shared validation function directly (e.g., use the shared
validator module rather than the local validatePayload) so requests that exceed
counts/lengths are rejected consistently across createDiscussion,
updateDiscussion and addComment handlers. Ensure error objects match the shared
validator shape (field + message) so callers receive consistent responses.
- Around line 21-36: The file-store is vulnerable to lost updates because
multiple handlers call readStore() → mutate → writeStore() concurrently; add a
single-process async mutex to serialize all read-modify-write operations (or
provide an atomic update API) so only one mutation runs at a time. Implement a
locked helper (e.g., updateStore or wrap writeStore) that acquires the mutex,
calls ensureDataFile(), reads/parses dataFile, applies an updater function to
the discussions array, writes the new JSON back, and releases the mutex; update
all callers to use this new locked updater instead of calling
readStore()/writeStore() separately. Keep references: readStore, writeStore,
ensureDataFile, dataFile, and the new updateStore(lock) helper so future
reviewers can find the changes.
- Around line 44-64: getCommunityIdentity currently returns a guest identity
that allows unauthenticated users to perform mutating actions; to fix this, stop
treating guests as authorized for writes by requiring authentication in mutating
handlers. Add an auth check (middleware or inline) that returns 401/403 when
req.user is missing for all endpoints that create/edit/delete/like/comment (the
route handlers for createDiscussion, editDiscussion, deleteDiscussion,
likeDiscussion, addComment or similarly named handlers referenced in the diff),
and keep getCommunityIdentity only for read operations (listing/fetching
discussions). Update routes to use the new auth guard for POST/PUT/DELETE
actions and remove any logic that uses req.session.communityUserId to authorize
writes.
- Around line 25-30: The catch block that swallows JSON.parse errors and returns
[] is dangerous because it masks corruption; in the function that parses raw
(the block using JSON.parse(raw) and checking parsed.discussions) stop treating
parse failures as an empty store—catch the error and rethrow or propagate it
(e.g., throw a new Error including the original error and context) so callers
can handle the failure instead of silently returning an empty array; update any
callers to handle the thrown error or to fail-safe without overwriting existing
discussions.

In `@src/pages/Community/Community.tsx`:
- Around line 125-131: The fetch success path currently updates setDiscussions
and setCategories but doesn't restore auth state after a prior 401; after a
successful response (where setDiscussions(response.data.items || []) and
setCategories(...) are called) call setIsAuthenticated(true) and clear any
previous error (e.g., setError("") or null) so the component reflects restored
authentication; leave the existing catch branch with
axios.isAxiosError(requestError) && requestError.response?.status === 401 to
still setIsAuthenticated(false).

In `@src/pages/Login/Login.tsx`:
- Line 7: The current backendUrl constant in Login.tsx falls back to
"http://localhost:5000", which breaks production clients; update the
initialization of backendUrl so it does not default to a localhost HTTP
address—either require import.meta.env.VITE_BACKEND_URL to be set and throw or
log a clear error, or derive a secure default (e.g., same-origin via
window.location.origin) for production; locate the backendUrl symbol in
Login.tsx and replace the fallback logic accordingly so production builds won't
silently point to http://localhost:5000.

---

Outside diff comments:
In `@backend/server.js`:
- Around line 25-29: The session middleware uses process.env.SESSION_SECRET
directly which can be undefined; validate and provide a non-empty secret (or
abort startup) before calling app.use(session(...)). Add code that reads
SESSION_SECRET into a variable, checks it's a non-empty string, and if missing
either throw an error/process.exit(1) or generate a secure fallback while
logging a clear warning; then pass that validated secret into the session config
used in app.use(session({ secret: secretVar, resave: false, saveUninitialized:
false })). Ensure the check runs at startup so the session middleware never
receives an undefined/empty secret.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5677e360-2280-4d2e-a9d0-9f4ad2c58bda

📥 Commits

Reviewing files that changed from the base of the PR and between 4ae0ef6 and e675744.

📒 Files selected for processing (13)
  • backend/data/discussions.json
  • backend/data/users.json
  • backend/models/Discussion.js
  • backend/routes/auth.js
  • backend/routes/discussions.js
  • backend/server.js
  • backend/validators/discussionValidator.js
  • src/App.tsx
  • src/Routes/Router.tsx
  • src/components/Navbar.tsx
  • src/pages/Community/Community.tsx
  • src/pages/Login/Login.tsx
  • src/pages/Signup/Signup.tsx

Comment thread backend/data/users.json
Comment thread backend/models/Discussion.js Outdated
Comment thread backend/routes/auth.js Outdated
Comment thread backend/routes/discussions.js
Comment thread backend/routes/discussions.js
Comment thread backend/routes/discussions.js
Comment thread backend/routes/discussions.js Outdated
Comment thread src/pages/Community/Community.tsx
Comment thread src/pages/Login/Login.tsx Outdated
@mehul-m-prajapati
Copy link
Copy Markdown
Collaborator

not required

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature Request: Add Community Discussion Section

2 participants